"""set_default_value

修订 ID: 0b2f6bf54834
父修订: 3a0f19b79fb5
创建时间: 2023-10-20 16:00:05.127379

"""
from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op
from alembic.op import run_async
from nonebot import logger, require
from sqlalchemy import Connection, inspect
from sqlalchemy.ext.asyncio import AsyncConnection
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session

revision: str = "0b2f6bf54834"
down_revision: str | Sequence[str] | None = "3a0f19b79fb5"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


default_shindan_records = [
    {
        "shindan_id": "162207",
        "command": "今天是什么少女",
        "title": "你的二次元少女化形象",
        "mode": "image",
    },
    {
        "shindan_id": "917962",
        "command": "人设生成",
        "title": "人设生成器",
        "mode": "image",
    },
    {
        "shindan_id": "790697",
        "command": "中二称号",
        "title": "奇妙的中二称号生成器",
        "mode": "image",
    },
    {
        "shindan_id": "587874",
        "command": "异世界转生",
        "title": "異世界轉生—∩開始的種族∩——",
        "mode": "image",
    },
    {
        "shindan_id": "940824",
        "command": "魔法人生",
        "title": "魔法人生：我在霍格沃兹读书时发生的两三事",
        "mode": "image",
    },
    {
        "shindan_id": "1075116",
        "command": "抽老婆",
        "title": "あなたの二次元での嫁ヒロイン",
        "mode": "text",
    },
    {
        "shindan_id": "400813",
        "command": "抽舰娘",
        "title": "【艦これ】あ なたの嫁になる艦娘は？",
        "mode": "image",
    },
    {
        "shindan_id": "361845",
        "command": "抽高达",
        "title": "マイ・ガンダム診断",
        "mode": "image",
    },
    {
        "shindan_id": "595068",
        "command": "英灵召唤",
        "title": "Fate 英霊召喚",
        "mode": "image",
    },
    {
        "shindan_id": "360578",
        "command": "卖萌",
        "title": "顔文字作るよ(  ﾟдﾟ )",
        "mode": "text",
    },
]


def _has_old_table(conn: Connection) -> bool:
    insp = inspect(conn)
    return "nonebot_plugin_shindan_shindanrecord" in insp.get_table_names()


def _read_old_data(conn: Connection) -> list[dict]:
    Base = automap_base()
    Base.prepare(autoload_with=conn)
    ShindanRecord = Base.classes.nonebot_plugin_shindan_shindanrecord

    shindan_records: list[dict] = []
    with Session(conn) as db_session:
        records = db_session.scalars(sa.select(ShindanRecord)).all()
        for record in records:
            shindan_records.append(
                {
                    "shindan_id": record.shindan_id,
                    "command": record.command,
                    "title": record.title,
                    "mode": record.mode,
                }
            )
    return shindan_records


def _insert_data(conn: Connection, shindan_records: list[dict]):
    Base = automap_base()
    Base.prepare(autoload_with=conn)
    ShindanRecord = Base.classes.nonebot_plugin_shindan_shindanrecord

    with Session(conn) as db_session:
        for record in shindan_records:
            db_session.add(
                ShindanRecord(
                    shindan_id=record["shindan_id"],
                    command=record["command"],
                    title=record["title"],
                    mode=record["mode"],
                )
            )
        db_session.commit()


_has_old_data = False


async def _migrate_old_data(conn: AsyncConnection):
    from nonebot_plugin_datastore.db import get_engine

    async with get_engine().connect() as ds_conn:
        if not await ds_conn.run_sync(_has_old_table):
            return
        shindan_records = await ds_conn.run_sync(_read_old_data)
        if not shindan_records:
            return

    global _has_old_data
    _has_old_data = True
    logger.info("shindan: 发现来自 datastore 的数据，正在迁移...")

    await conn.run_sync(_insert_data, shindan_records)

    logger.info("shindan: 迁移完成")


def upgrade(name: str = "") -> None:
    if name:
        return
    # ### commands auto generated by Alembic - please adjust! ###

    try:
        require("nonebot_plugin_datastore")

        run_async(_migrate_old_data)
    except (RuntimeError, ImportError, ModuleNotFoundError):
        pass

    if not _has_old_data:
        _insert_data(op.get_bind(), default_shindan_records)

    # ### end Alembic commands ###


def downgrade(name: str = "") -> None:
    if name:
        return
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###
